package com.example.controller;

import com.example.entity.Bill;
import com.example.entity.BillType;
import com.example.service.BillService;
import com.example.service.TypeService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: huang
 * @Date: 2021/11/1 20:27
 * @Description:
 */
@Controller
public class BillController {

    @Resource
    private BillService billService;

    @Resource
    private TypeService typeService;

    @RequestMapping(path = "/list", method = RequestMethod.GET)
    public String list(Bill b, Model model) {
        List<BillType> types = typeService.list();
        model.addAttribute("types", types);

        List<Bill> bills = billService.list(b);
        model.addAttribute("bills", bills);

        return "bill/list";
    }

    /**
     * 跳到添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd(Model model) {
        //查询账单类型，添加到视图，用于选择账单类型
        List<BillType> types = typeService.list();
        model.addAttribute("types", types);
        return "bill/add";
    }


    /**
     * 添加账单
     * @param b
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(Bill b) {
        billService.add(b);
        //重定向到list页面
        return "redirect:/bill/list";
    }

    @RequestMapping(path = "/deete/{id}", method = RequestMethod.POST)
    public String delete(@PathVariable("id")long id) {
        billService.delete(id);
        //重定向到list页面
        return "redirect:/bill/list";
    }

    @RequestMapping(path = "/toUpdate/{id}", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("id")long id, Model model) {
        List<BillType> types = typeService.list();
        model.addAttribute("types", types);

        Bill bill = billService.get(id);
        model.addAttribute("bill", bill);
        return "/bill/update";
    }

    @RequestMapping(path = "update", method = RequestMethod.POST)
    public String uodate(Bill b) {
        billService.update(b);
        return "redirect:/bill/list";
    }

}
